import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";
import router from "../routes.js";
const cachios = require('cachios');
const Axios = axios.create({
    baseURL: "http://liveservice.100jv.com/api/admin", // 因为我本地做了反向代理
    timeout: 10000,
    responseType: "json",
    withCredentials: false, // 不需要cookie
});

const cachiosInstance = cachios.create(Axios, {
    stdTTL: 2,
    // checkperiod: 0,
});
function redLogin() {
    setTimeout(()=>{
        router.push({
            path: "/login"
        });
    }, 2000);
}
//POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
    config => {
        // 在发送请求之前做某件事
        if (
            config.method === "post" ||
            config.method === "put" ||
            config.method === "delete"
        ) {
            // 序列化
            config.data = qs.stringify(config.data);
        }

        // 若是有做鉴权token , 就给头部带上token
        let api_token = localStorage.getItem("api_token");
        if (api_token) {
            config.headers.Authorization = 'Bearer' + ' ' + api_token;
        }
        return config;
    },
    error => {
        Message({
            //  饿了么的消息弹窗组件,类似toast
            showClose: true,
            message: error,
            type: "error.data.error.message"
        });
        return Promise.reject(error.data.error.message);
    }
);
// //返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
    res => {
        if (res.data.status == -10) {
            Message({
                //  饿了么的消息弹窗组件,类似toast
                showClose: true,
                message: '请先登录！',
                type: "error"
            });
            // 若是接口访问的时候没有发现有鉴权的基础信息,直接返回登录页
            redLogin();
        }
        return res;
    },
    error => {
        if (!window.localStorage.getItem("api_token")) {
            redLogin();
        } else {
            if (error.response.status === 401) {
                redLogin();
            }
            if (error.response.status === 403) {
                router.push({
                    path: "/error/403"
                });
            }
            // if (error.response.status === 500) {
            //     router.push({
            //         path: "/error/500"
            //     });
            // }
            // if (error.response.status === 502) {
            //     router.push({
            //         path: "/error/502"
            //     });
            // }
            // if (error.response.status === 404) {
            //     router.push({
            //         path: "/error/404"
            //     });
            // }
        }
        // 返回 response 里的错误信息
        let errorInfo =  error.response.data.msg;
        return Promise.reject(errorInfo);
    }
);


export default {
    install: function(Vue) {
        Object.defineProperty(Vue.prototype, "$http", { value: cachiosInstance });
    }
};